<template>
  <div class="min-h-screen p-2 bg-gradient-to-r bg-white">
    <div class="max-w-5xl mx-auto bg-white rounded-xl shadow-sm overflow-hidden">
      <!-- 标题栏 -->
      <div class="bg-blue-600 px-6 py-4">
        <h1 class="text-xl font-semibold text-white">退供应商物流单号填写</h1>
      </div>
    </div>
    <!-- 主要内容区 -->
    <div class="p-4 space-y-6">
      <!-- 第一行：基本信息 -->
      <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div class="space-y-1">
          <p class="text-xl font-semibold text-gray-500">门店名称</p>
          <p class="font-medium text-xl">{{ formData.storeName || '--' }}</p>
        </div>
        <div class="space-y-1">
          <p class="text-xl font-semibold text-gray-500">提报人</p>
          <p class="font-medium text-xl">{{ formData.staffName || '--' }}</p>
        </div>
        <div class="space-y-1">
          <p class="text-xl font-semibold text-gray-500">残次单号</p>
          <p class="font-medium text-xl">{{ formData.billId || '--' }}</p>
        </div>
        <div class="space-y-1" v-if="formData.oaBillId">
          <p class="text-xl font-semibold text-gray-500">钉钉单号</p>
          <p class="font-medium text-xl">{{ formData.oaBillId }}</p>
        </div>
      </div>

      <!-- 第二行：商品信息 -->
      <div class="grid grid-cols-2 md:grid-cols-5 gap-4">
        <div class="space-y-1">
          <p class="text-xl font-semibold text-gray-500">商品名称</p>
          <p class="font-medium text-xl">{{ formData.itemName || '--' }}</p>
        </div>
        <div class="space-y-1">
          <p class="text-xl font-semibold text-gray-500">商品编号</p>
          <p class="font-medium text-xl">{{ formData.itemId || '--' }}</p>
        </div>
        <div class="space-y-1">
          <p class="text-xl font-semibold text-gray-500">商品品类</p>
          <p class="font-medium text-xl">{{ formData.className || '--' }}</p>
        </div>
        <div class="space-y-1">
          <p class="text-xl font-semibold text-gray-500">商品价格</p>
          <p class="font-medium text-xl text-red-600">{{ formData.sellPrice ? `¥${formData.sellPrice}` : '--' }}</p>
        </div>
        <div class="space-y-1">
          <p class="text-xl font-semibold text-gray-500">残次品数量</p>
          <p class="font-medium text-xl text-red-600">{{ formData.posQty }}</p>
        </div>
      </div>

      <div class="grid grid-cols-2 md:grid-cols-5 gap-4">
        <div class="space-y-1">
          <p class="text-xl font-semibold text-gray-500">运单号</p>
          <p class="font-medium text-xl" style="color: red">{{ formData.ydh !== ' ' ?  formData.ydh : '无' }}</p>
        </div>
        <div class="space-y-1">
          <p class="text-xl font-semibold text-gray-500">箱号</p>
          <p class="font-medium text-xl" style="color: red">{{ formData.xh !== ' ' ? formData.xh : '无' }}</p>
        </div>
      </div>
      <div class="flex gap-4 text-center justify-center">
        <p class="text-xl font-semibold text-gray-500 ">残次审核状态</p>
        <p class="font-medium text-xl" v-if="formData.shStatus === '999'">已终止</p>
        <p class="font-medium text-xl" v-if="formData.shStatus === '000'">门店未确认</p>
        <p class="font-medium text-xl" v-if="formData.shStatus === '001'">门店已确认</p>
        <p class="font-medium text-xl" v-if="formData.shStatus === '002'">区域经理已审核</p>
        <p class="font-medium text-xl" v-if="formData.shStatus === '003'">物流部已审核</p>
      </div>

      <div class="flex gap-4 text-center justify-center" v-if="formData.wlBillId">
        <p class="text-xl font-semibold text-gray-500 ">物流单号</p>
        <p class="font-medium text-xl">{{ formData.wlBillId }}</p>
      </div>
      <div class="flex gap-4 text-center justify-center">
        <p class="text-xl font-semibold text-gray-500 ">提报时间</p>
        <p class="font-medium text-xl">{{ formData.uptime || '2023-06-15 14:30' }}</p>
      </div>


      <!-- 第三行：残次描述 -->
      <div class="border rounded-lg p-2">
        <p class="text-xl text-gray-500 mb-2">残次描述</p>
        <p class="text-sm leading-5" style="color: red; font-weight: bold">{{ formData.remark || '--' }}</p>
      </div>

      <!-- 新增：物流单号输入 -->
      <div class="border rounded-lg p-2">
        <label class="block text-xl text-gray-500 mb-2">请输入物流单号(注意：运费到付)</label>
        <input
            type="text"
            v-model="formData.wlInfoId"
            placeholder="请填写物流单号"
            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
        >
      </div>

      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div class="border rounded-lg p-4">
          <p class="text-xl text-gray-500 mb-2">请将打包好的商品包裹拍摄视频</p>
          <div v-if="formData.bffj?.trim()" class="aspect-video bg-black rounded overflow-hidden">
            <video controls class="w-full h-full">
              <source :src="formData.bffj" type="video/mp4">
            </video>
          </div>
          <div v-else class="text-gray-400 text-sm py-8 text-center">
            暂无视频,待上传
          </div>
        </div>
      </div>

      <!-- 视频上传 -->
      <div>
        <!-- 视频预览 -->
        <video
            v-if="videoPreviewUrl"
            :src="videoPreviewUrl"
            controls
            class="w-full mt-4 bg-white rounded-lg border border-gray-200" style="height: 400px">
        </video>

        <!-- 操作按钮 -->
        <div class="flex w-full space-x-5 mt-4">
          <button
              @click="triggerVideoInput"
              class="w-full bg-yellow-500 text-white px-2 py-3 rounded-lg transition duration-200">
            拍摄包裹视频
          </button>

          <!--        <button-->
          <!--            v-if="videoPreviewUrl"-->
          <!--            @click="uploadVideo"-->
          <!--            class="w-full bg-green-500 text-white px-2  py-3 rounded-lg transition duration-200 ">-->
          <!--          上传视频-->
          <!--        </button>-->
        </div>

        <!-- 进度条 -->
        <div v-if="uploadProgress.percent  > 0" class="mt-2">
          <div class="text-sm text-gray-600 mb-1">
            上传进度: {{ uploadProgress.percent }}%
          </div>
          <div class="progress-bar">
            <div
                class="progress"
                :style="{ width: `${uploadProgress.percent}%`  }">
            </div>
          </div>
        </div>
        <!-- 隐藏的input元素 -->
        <input
            type="file"
            ref="videoInput"
            accept="video/*"
            capture="environment"
            class="hidden"
            @change="handleVideoSelected">
      </div>

      <!-- 审核操作 -->
      <div class="flex flex-col sm:flex-row justify-end gap-3 pt-4 border-t">
        <button
            @click="handleReset"
            :class="['px-4 py-2 text-sm rounded transition bg-gray-200 text-gray-500 cursor-not-allowed',]"
        >
          重置
        </button>
        <button
            @click="handleSubmit"
            :class="['px-4 py-2 text-sm rounded transition bg-blue-600 text-white hover:bg-blue-700',]"
        >
          提交
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
// 组件挂载时获取数据
import {onMounted, ref} from "vue";
import {useRoute} from "vue-router";
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";

const route = useRoute();
const loading = ref(true);
const error = ref(null)
const prefixUrl = ref("https://mms.mumuso.com:8214/dingTalkWebProject/api/file/");
// 响应式数据
const formData = ref({
  storeName: '',
  reporter: '',
  billId: '',
  oaBillId: '',
  itemName: '',
  itemId: '',
  className: '',
  sellPrice: 0,
  uptime: '',
  remark: '',
  fj: '',
  staffId: '',
  areaStaff: '',
  shStatus: '',
  storeId: '',
  cgStaff: '',
  staffName: '',
  wlBillId: null,
  wlInfoId: '',
  bffj: '',
  posQty: null
});

// 定义预览视频
const videoPreviewUrl = ref(null);
const videoFile = ref(null);
// 响应式数据
const videoInput = ref(null);
const uploadProgress = ref({
  loaded: 0,
  total: 0,
  percent: 0
});

const handleVideoSelected = (event) => {
  const file = event.target.files[0];
  if (!file) return;

  // 验证文件类型
  if (!file.type.startsWith('video/')) {
    ElMessageBox.alert(' 请选择有效的视频文件', '提示');
    return;
  }

  // 验证文件大小
  const maxSize = 100 * 1024 * 1024; // 100MB
  if (file.size > maxSize) {
    ElMessageBox.alert(' 视频大小不能超过100MB', '提示');
    return;
  }

  // 存储文件
  videoFile.value = file;

  // 创建预览
  videoPreviewUrl.value = URL.createObjectURL(file);

  // 重置input
  event.target.value = '';
};

// 方法定义
const triggerVideoInput = () => {
  videoInput.value.click();
};
// 获取残次单详情
const fetchDefectDetail = async (billId) => {
  try {
    loading.value = true
    const response = await axios.get(`https://mms.mumuso.com:8214/dingTalkWebProject/reported/getReportedInfo/${billId}`)
    if (response.data.code === 200) {
      formData.value = response.data.data
      if (formData.value.bffj?.trim())  {  // 同时处理 null/undefined/空字符串/纯空格
        formData.value.bffj  = prefixUrl.value  + formData.value.bffj.trim();
      }
    } else {
      ElMessageBox.alert(response.data.msg, {
        type: "error",
        confirmButtonText: "确认",
        customClass: "my-custom-error",
      });
    }

  } catch (err) {
    error.value = err.response?.data?.message || '获取数据失败'
    console.error(' 获取残次单详情失败:', err)
  } finally {
    loading.value = false
  }
}

// 重置按钮
const handleReset = () => {
  formData.value.wlInfoId = '';
  videoPreviewUrl.value = null;
  videoFile.value = null;
}

// 提交按钮
const handleSubmit = async () => {
  try {
    // 传递单号和物流单号品类
    if (!formData.value.wlInfoId) {
      await ElMessageBox.alert("物流单号不能为空，请填写物流单号!", {
        type: "error",
        confirmButtonText: "确认",
        customClass: "my-custom-error",
      });
      return;
    }

    if (!videoFile.value) {
      await ElMessageBox.alert("你还未拍摄报废视频，", {
        type: "error",
        confirmButtonText: "确认",
        customClass: "my-custom-error",
      });
      return;
    }
    // 添加确认对话框并等待用户选择
    await ElMessageBox.confirm(
        `确定要提交当前残次单【${formData.value.billId} 】的包裹视频和物流单号吗？`,
        '确认通过',
        {
          confirmButtonText: '确定通过',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )
    const formInfo = new FormData();
    formInfo.append('file', videoFile.value);
    // 2. 追加其他字段（JSON格式）
    formInfo.append('data', new Blob([JSON.stringify({
      billId: formData.value.billId,
      wlInfoId: formData.value.wlInfoId,
      className: formData.value.className,
      cgStaff: formData.value.cgStaff,
      remark: formData.value.remark,
      storeName: formData.value.storeName,
      itemName: formData.value.itemName,
      staffId: formData.value.staffId,
      staffName: formData.value.staffName,
      areaStaff: formData.value.areaStaff,
      wlBillId: formData.value.wlBillId
      // 其他非文件字段...
    })], {type: 'application/json'}));
    const response = await axios.put('https://mms.mumuso.com:8214/dingTalkWebProject/reported/submitWlInfo', formInfo,
        {
          headers: {
            'Content-Type': 'multipart/form-data', // 必须修改
            'X-Request-From': 'web'
          }
        }
    )
    if (response.data.code === 200) {
      await ElMessageBox.alert(response.data.msg, {
        type: "success",
        confirmButtonText: "确认",
        customClass: "my-custom-error",
      });
      await fetchDefectDetail(formData.value.billId);
      // 提交完之后将物流单号和预览视频删除
      await handleResetVideoData();
    } else {
      await ElMessageBox.alert(response.data.msg, {
        type: "warning",
        confirmButtonText: "确认",
        customClass: "my-custom-error",
      });
    }

    // 填写完物流单号之后发送更新请求
  } catch (error) {
    // 用户点击取消按钮
    if (error === 'cancel' || error.message?.includes('cancel')) {
      return // 静默退出，不显示错误
    }
    // 处理其他错误
    const errorMsg = error.response?.data?.message || error.message || '审核操作失败'
    ElMessage.error(` 审核失败: ${errorMsg}`)
    console.error(' 审核通过失败:', error)
  }
}

const handleResetVideoData = () => {
  formData.value.wlInfoId = '';
  videoFile.value = null;
  videoPreviewUrl.value = null;
}

onMounted(() => {
  // 从路由参数中获取残次单号
  const billId = route.query.billId;
  // 获取提报人编号
  const staffId = route.query.staffId;
  localStorage.setItem("staffId", staffId);

  if (billId) {
    fetchDefectDetail(billId)
  } else {
    error.value = '未提供残次单号'
    loading.value = false
  }
});
</script>